package com.jokins.admin.vue.hefeng.action;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jokins.admin.vue.hefeng.actioncontext.GetToDayWeatherDoc;
import com.jokins.admin.vue.hefeng.mapper.CityMapper;
import com.jokins.admin.vue.hefeng.mapper.WeatherMapper;
import com.jokins.admin.vue.hefeng.utils.GetWeatherToDay;
import com.jokins.admin.vue.hefeng.vo.WeatherVo;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.hefeng.City;
import com.jokins.common.entry.hefeng.Weather;
import com.jokins.common.util.BusinessCode;
import com.jokins.common.util.SqlTypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class GetToDayWeatherDocAction extends BaseAction<GetToDayWeatherDoc> {

    @Autowired
    WeatherMapper weatherMapper;

    @Autowired
    CityMapper cityMapper;

    @Override
    protected void process(GetToDayWeatherDoc actionContext) throws BusinessException {
        String cityId = actionContext.getCityId();
        WeatherVo weatherVo = new WeatherVo();
        QueryWrapper<Weather> weatherQueryWrapper = new QueryWrapper<>();
        weatherQueryWrapper.eq("city_id", cityId);
        // 获取此时时间
        Date now = new Date();
        weatherQueryWrapper.eq("created_time", now);
        Weather weather=new Weather();
        weather=weatherMapper.selectOne(weatherQueryWrapper);
        if (weather != null) {
            log.info("数据库中存在该城市天气数据,直接返回");
            SqlTypeConverter.copyEntity(weather,weatherVo);
            actionContext.setResult(ActionContext.RESULT_DOC_KEY, JSON.parseObject(JSON.toJSONString(weather), WeatherVo.class));
            return;
        }
        log.info("数据库中没有该城市天气数据,调用接口获取数据");
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("city_id", cityId);
        City city = cityMapper.selectOne(queryWrapper);
        if (city == null) {
            throw new BusinessException("城市ID不存在", BusinessCode.PARAM_ERROR);
        }
        weather = GetWeatherToDay.API(cityId);
        weather.setName(city.getCountry()+"-"+city.getAdm1()+"-"+city.getAdm2()+"-"+city.getName());
        weatherMapper.insert(weather);
        SqlTypeConverter.copyEntity(weather,weatherVo);
        log.info("写入成功！,返回成城市:{},天气数据:{}",JSON.toJSONString(weather.getName()), JSON.toJSONString(weatherVo));
        actionContext.setResult(ActionContext.RESULT_DOC_KEY,weatherVo);
    }
}
